<script setup lang="ts">
import type { DateList } from './interface';

import { computed, ref, watch } from 'vue';

import { MdiMinus2, MdiPlus2 } from '@vben/icons';

import {
  InputNumber,
  message,
  Modal,
  Radio,
  RadioGroup,
  RangePicker,
} from 'ant-design-vue';
import dayjs from 'dayjs';

import { updateRoomStock } from '#/api';

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  data: {
    type: Object as () => DateList,
    default: () => ({}),
  },
});

const emit = defineEmits(['update:show', 'upList']);

const open = computed({
  get() {
    return props.show;
  },
  set(newValue) {
    emit('update:show', newValue);
  },
});

// 房态列表
const roomStates = ref<null | number>(1);
// 售卖模式
const saleMode = ref<null | number>(1);
// 剩余保留房房量
const remainingReservedRoom = ref<number | string>();
// 加载
const confirmLoading = ref(false);

// 日期范围
const dateRange = ref<[string, string][]>([['', '']]);

// 禁用当天之前的日期
const disabledDate = (current: dayjs.Dayjs) => {
  return current && current < dayjs().startOf('day');
};

// 选择日期范围
const dateChange = (e: any, index: number) => {
  dateRange.value[index] = e.map((item: any) =>
    dayjs(item).format('YYYY-MM-DD'),
  );
};

watch(
  () => props.data,
  (val) => {
    if (val) {
      dateRange.value = [[val.saleDate, val.saleDate]];
      roomStates.value = val.roomStatus;
      saleMode.value = val.saleMode;
      remainingReservedRoom.value =
        val.quotaCount === null ? '' : val.quotaCount;
    }
  },
  {
    immediate: true,
  },
);

// 点击确定按钮事件提交表单 成功后关闭弹窗
const handleOk = async () => {
  confirmLoading.value = true;
  try {
    const timeList =
      dateRange.value?.map((item) => ({
        startTime: item[0],
        endTime: item[1],
      })) || [];
    await updateRoomStock({
      quotaCount: remainingReservedRoom.value,
      roomStatus: roomStates.value,
      roomTypeId: [props.data.roomId],
      saleMode: saleMode.value,
      timeList,
    });
    confirmLoading.value = false;
    open.value = false;
    message.success('修改成功');
    emit('upList');
  } catch (error) {
    confirmLoading.value = false;
    console.error('房态设置失败：', error);
  }
};
</script>

<template>
  <Modal
    v-model:open="open"
    :confirm-loading="confirmLoading"
    title="设置房态"
    width="800px"
    @ok="handleOk"
  >
    <div class="card-box mb-3 mt-2 max-h-[70vh] overflow-y-auto rounded-none">
      <div class="flex">
        <div class="w-[150px] bg-black bg-opacity-5 p-3 font-bold">
          房型名称
        </div>
        <div class="flex-auto p-3">{{ data.nameZh || '' }}</div>
      </div>
      <div class="flex border-t">
        <div class="w-[150px] bg-black bg-opacity-5 p-3 font-bold">日期</div>
        <div class="flex-auto p-3">
          <div
            v-for="(item, index) in dateRange"
            :key="index"
            class="mt-3 flex w-full flex-wrap items-center"
          >
            <RangePicker
              :disabled-date="disabledDate"
              :value="
                item[0] && item[1]
                  ? [dayjs(item[0], 'YYYY-MM-DD'), dayjs(item[1], 'YYYY-MM-DD')]
                  : undefined
              "
              @change="dateChange($event, index)"
            />
            <MdiMinus2
              v-if="dateRange.length !== 1"
              class="text-primary ml-2 cursor-pointer text-3xl"
              @click="() => dateRange.splice(index, 1)"
            />
            <MdiPlus2
              v-if="index === dateRange.length - 1"
              class="text-primary ml-2 cursor-pointer text-3xl"
              @click="() => dateRange.push(['', ''])"
            />
          </div>
        </div>
      </div>
      <div class="flex border-t">
        <div class="w-[150px] bg-black bg-opacity-5 p-3 font-bold">
          设置房态
        </div>
        <div class="flex-auto p-3">
          <RadioGroup
            v-model:value="roomStates"
            class="flex items-center"
            name="roomStates"
          >
            <Radio
              :class="[roomStates === 1 ? 'border-primary' : '']"
              :value="1"
              class="flex min-w-[160px] items-center rounded-md border p-2"
            >
              <div class="text flex items-center">
                <span class="bg-primary mr-2 flex h-[20px] w-[20px]"></span>
                有房
              </div>
            </Radio>
            <Radio
              :class="[roomStates === 2 ? 'border-primary' : '']"
              :value="2"
              class="ml-1 flex min-w-[160px] items-center rounded-md border p-2"
            >
              <div class="text flex items-center">
                <span class="mr-2 flex h-[20px] w-[20px] bg-red-500"></span>
                满房
              </div>
            </Radio>
          </RadioGroup>
        </div>
      </div>
      <template v-if="roomStates === 1">
        <div class="flex border-t">
          <div class="w-[150px] bg-black bg-opacity-5 p-3 font-bold">
            售卖模式
          </div>
          <div class="mode flex-auto p-3">
            <RadioGroup v-model:value="saleMode" name="saleMode">
              <Radio :value="1">
                <div class="text">
                  <p>限量</p>
                  <p class="opacity-50">仅售卖保留房间数，保留房售完停止售卖</p>
                </div>
              </Radio>
              <Radio :value="2">
                <div class="text">
                  <p>FreeSale</p>
                  <p class="opacity-50">按照保留房不限畅卖</p>
                </div>
              </Radio>
            </RadioGroup>
          </div>
        </div>
        <div class="flex border-t">
          <div class="w-[150px] bg-black bg-opacity-5 p-3 font-bold">
            剩余保留房房量
          </div>
          <div class="flex flex-auto items-center p-3">
            设置为
            <InputNumber
              v-model:value="remainingReservedRoom"
              :max="9999"
              :min="0"
              class="mx-2"
            />
            间 当前剩余
            <span class="text-primary mx-1">{{ data.quotaCount || 0 }}</span> 间
          </div>
        </div>
      </template>
    </div>
  </Modal>
</template>

<style scoped lang="scss">
.text {
  color: hsl(var(--card-foreground));
}

// :deep(.mode .ant-radio) {
//   margin-top: -24px;
// }
</style>
